package com.ccteam.admin.repositories

import com.ccteam.admin.vo.Resource
import com.ccteam.network.ApiError
import com.ccteam.network.ApiResult

/**
 * @author Xiaoc
 * @since 2021/2/18
 *
 * 用于Suspend一次性请求的决策操作
 * 简化了操作，防止每一次写样板代码
 *
 * @param ResponseResult 需要返回的数据类型
 * @param RequestResult 请求网络要返回的数据类型
 */
abstract class BaseSuspendResource<ResponseResult,RequestResult> {

    suspend fun asResource(): Resource<ResponseResult>{
        return when(val networkResult = handleNetwork()){
            is ApiResult.Success ->{
                Resource.Success(processResponse(networkResult))
            }
            is ApiResult.Empty ->{
                Resource.Error(ApiError.dataIsNull.errorMsg,null)
            }
            is ApiResult.Failure ->{
                Resource.Error(networkResult.errorMsg)
            }
        }
    }

    abstract suspend fun handleNetwork(): ApiResult<RequestResult>

    abstract fun processResponse(response: ApiResult.Success<RequestResult>): ResponseResult
}